import { createRouter, createWebHashHistory, RouteRecordRaw } from "vue-router";

const routes: RouteRecordRaw[] = [
  {
    path: "/login",
    component: () => import("../views/Login/Login.vue"),
    meta: {
      isPublic: true,
    },
  },
  {
    path: "/",
    component: () => import("../views/Index/Index.vue"),
    children: [
      {
        path: "/",
        redirect: "/orders/list",
      },
      {
        path: "/:resource/list",
        component: () => import("../views/CRUD/List.vue"),
        props: true,
      },
      {
        path: "/:resource/create",
        component: () => import("../views/CRUD/Edit.vue"),
        props: true,
      },
      {
        path: "/:resource/edit/:id",
        component: () => import("../views/CRUD/Edit.vue"),
        props: true,
      },
    ],
  },
];

const router = createRouter({
  history: createWebHashHistory(),
  routes,
});

router.beforeEach((to) => {
  if (!to.meta.isPublic && !localStorage.getItem("token")) {
    return "/login";
  }
});

export { router };
